/*
 * Copyright (c) 2006, 2023, webrx.cn All rights reserved.
 *
 */
package cn.webrx.config;

import cn.webrx.interceptor.KeyGen;
import cn.webrx.interceptor.MyPager;
import cn.webrx.utils.SnowFlakeUtils;
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;

import java.io.IOException;
import java.time.LocalDate;
import java.util.Properties;

/**
 * <p></p>
 * <p>Powered by webrx On 2023-04-19 14:19:11</p>
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
@Configuration
@MapperScan({"cn.webrx.mapper"})
@ComponentScan("cn.webrx")

public class AppConfig {
    private String url = "jdbc:mysql:/db";
    private String username = "root";
    private String password = "root";

    @Bean
    public LocalDate now() {
        return LocalDate.now();
    }

    @Bean(name = "ds", initMethod = "init", destroyMethod = "close")
    public DruidDataSource druidDataSource() {
        DruidDataSource ds = new DruidDataSource();
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return ds;
    }

    @Bean("sf")
    public SqlSessionFactoryBean sqlSessionFactoryBean(DruidDataSource ds, MyPager mp, KeyGen kg) throws IOException {
        SqlSessionFactoryBean sf = new SqlSessionFactoryBean();
        sf.setDataSource(ds);

        //设置别名 cn.webrx.entity.Book 别名就 book cn.webrx.vo.BookVo 别名就是 bookVo bookvo
        sf.setTypeAliasesPackage("cn.webrx.entity,cn.webrx.vo");

        //注册PageHelper插件


        //sf.setPlugins(new ExamplePlugin(), mp, new PageInterceptor());
        //sf.setPlugins(kg);

        sf.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*Mapper*.xml"));
        return sf;
    }

    @Bean
    public SqlSession sqlSession(SqlSessionFactoryBean sf) throws Exception {
        return sf.getObject().openSession();
    }

    @Bean
    public MyPager myPager(SnowFlakeUtils su) {
        MyPager mp = new MyPager();
        mp.setSu(su);
        Properties prop = new Properties();
        prop.setProperty("currpage", "1");
        prop.setProperty("pagesize", "3");
        mp.setProperties(prop);
        return mp;
    }

    @Bean
    public KeyGen keyGen(SnowFlakeUtils su) {
        KeyGen kg = new KeyGen();
        kg.setSu(su);
        return kg;
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer ms = new MapperScannerConfigurer();
        ms.setBasePackage("cn.webrx.mapper");
        return ms;
    }
}
